package org.qy.star_server.util;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import org.qy.star_common.message.Message;
import org.qy.star_common.message.MessageProperties;

/**
 * @author yinger
 * @description 提供 protobuf 的序列化和反序列化方法
 * @date 2024/3/26 11:49
 **/
public class ProtoUtil {
    public static Message parseMessage(byte[] bytes) {
        try {
            // 1. 将字节数组读取成ProtoBuf对象
            MessageProto.Message message = MessageProto.Message.parseFrom(bytes);
            // 2. 将ProtoBuf对象转换为Message对象
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setMessageId(message.getMessageId());
            messageProperties.setRoutingKey(message.getRoutingKey());
            messageProperties.setDeliveryMode(message.getDeliveryMode());
            return new Message(messageProperties, message.getBody().toByteArray(), (byte) message.getValid());
        } catch (InvalidProtocolBufferException e) {
            System.out.println("反序列化失败" + e.getMessage());
            return null;
        }
    }

    public static byte[] serializeMessage(Message message) {
        try {

            MessageProto.Message.Builder builder = MessageProto.Message.newBuilder();
            // 1. 构建数据
            builder.setBody(ByteString.copyFrom(message.getBody()))
                    .setDeliveryMode(message.getDeliveryMode())
                    .setMessageId(message.getMessageId())
                    .setRoutingKey(message.getRoutingKey())
                    .setValid(message.getValid())
                    .build();
            // 2.序列化
            MessageProto.Message build = builder.build();
            return build.toByteArray();
        } catch (Exception e) {
            System.out.println("序列化失败" + e.getMessage());
            return null;
        }
    }
}
